<template>
  <div class="template-A">
    <el-form :model="formlist" label-width="auto" style="display: flex; align-items: center">
      <!-- <div style="display: flex;"> -->
      <el-form-item label="模板名称:">
        <el-input v-model="formlist.reportName" placeholder="请输入" style="width: 200px" />
      </el-form-item>
      <el-form-item label="报告类型:" style="margin-left: 50px">
        <el-select
          v-model="formlist.reportCode"
          class="!w-240px"
          clearable
          placeholder="请选择报告类型"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.REPORT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: 50px">
        <el-button type="primary" @click="query">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
      <!-- </div> -->
    </el-form>
    <div>
      <el-form-item style="display: flex">
        <el-button type="primary" @click="uploadTemplate">上传模板</el-button>
        <el-button type="primary" @click="remove">删除</el-button>
        <el-button type="primary" @click="onDownload">下载</el-button>

        <el-dialog v-model="dialogVisible" width="700">
          <h2 style="color: #000; font-weight: 700; margin: 0; padding: 0">新增报告模板</h2>
          <el-divider style="margin: 10px 0; padding: 0" />
          <el-form
            ref="ruleFormRef"
            :model="addList"
            :rules="addListCheck"
            label-width="auto"
            class="demo-ruleForm"
            :size="formSize"
            status-icon
          >
            <el-form-item label="模板名称" prop="templateNmae">
              <el-input
                v-model="addList.templateNmae"
                style="width: 400px"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label="报告类型" prop="statusType" style="margin-top: 30px">
              <el-select
                v-model="addList.reportCode"
                class="!w-400px"
                clearable
                placeholder="请选择报告类型"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.REPORT_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="报告文件名称" prop="typeNmae" style="margin-top: 30px">
              <el-input
                v-model="addList.typeNmae"
                style="width: 400px"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="文件类型"
              v-model="addList.fileType"
              prop="fileType"
              style="margin-top: 30px"
            >
              <el-select
                v-model="addList.fileType"
                class="!w-400px"
                clearable
                placeholder="请选择文件类型"
              >
                <el-option
                  v-for="(item, index) in typeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="模板" style="margin-top: 30px">
              <el-upload
                class="upload-demo"
                :file-list="fileList"
                ref="upload"
                accept=".doc,.docx"
                action=""
                :http-request="uploadFile"
                limit="1"
                :before-remove="beforeRemove"
              >
                <el-button type="primary">选择文件</el-button>
              </el-upload>
            </el-form-item>
          </el-form>
          <div style="margin-top: 50px; display: flex; justify-content: center">
            <el-button v-if="flag" type="primary" @click="onStorage" size="default">保存</el-button>
            <el-button v-else type="primary" @click="modify" size="default">修改</el-button>
            <el-button @click="onClose" size="default">关闭</el-button>
          </div>
        </el-dialog>
      </el-form-item>
    </div>
    <div style="margin-top: 20px">
      <el-table
        :data="tableData"
        style="width: 100%"
        show-header
        @selection-change="handleSelectionChange"
        stripe
        header-cell-class-name="custom-header"
      >
        <el-table-column type="selection" />
        <el-table-column prop="reportName" label="模板名称" width="400" align="center" />
        <el-table-column prop="reportCode" label="报告类型" align="center" />
        <el-table-column prop="fileTypeName" label="文件类型" align="center" />
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <el-button type="text" @click="view(row)" class="btn">预览</el-button>
            <el-button type="text" @click="edit(row)" class="btn">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 30px">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- <embed id="pdfViewer" type="application/pdf" width="100%" height="600px"> -->
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElFormItem, ElInput, ElButton } from 'element-plus'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { ElMessage, ElMessageBox } from 'element-plus'
defineOptions({ name: 'SystemDictType' })
import * as datarApi from '@/api/report'
import moment from 'moment'
import download from '@/utils/download'
// import { blob } from 'stream/consumers';
// 对话框控制
const dialogVisible = ref(false)
// 文件类型
let typeList = []
// 删除项
let idList = []
// 下载
let fileidList = []
let filename = []
// 清空
const upload = ref(null) // 通过 ref 创建对 el-upload 组件的引用
// 查询条件forml
const formlist = reactive({
  reportName: '',
  reportCode: '',
  pageSize: '10',
  pageNo: '1',
  total: ''
})
const fileList = ref([]) // 响应式的 fileList

const flag = ref(true)
// 模板管理表格
const tableData = ref([])
// 新增模板数据
const addList = reactive({
  templateNmae: '',
  reportCode: '',
  typeNmae: '',
  fileType: '',
  template: '',
  file: '',
  fileId: ''
})
// const fileList = reactive([])
// 新增模板校验
const addListCheck = reactive({
  templateNmae: [{ required: true, message: '不可为空', trigger: 'blur' }],
  reportCode: [{ required: true, message: '不可为空', trigger: 'blur' }],
  typeNmae: [{ required: true, message: '不可为空', trigger: 'blur' }],
  fileType: [{ required: true, message: '不可为空', trigger: 'blur' }],
  template: [{ required: true, message: '不可为空', trigger: 'blur' }]
})
// 分页
const currentPage = ref('')
const pageSize = ref('')
const pageNo = ref('')
const size = ref('default')
const disabled = ref(false)
const background = ref(false)
const total = ref('')
// top1按钮区域
// 查询
const query = () => {
  getDataList()
}
// 重置
const reset = () => {
  formlist.reportName = ''
  formlist.reportCode = ''
}
// top2按钮区域
// 上传模板
const uploadTemplate = async () => {
  fileList.value = []
  flag.value = true
  dialogVisible.value = true
  getfileTypeList()
  addList.templateNmae = ''
  addList.id = ''
  addList.reportCode = ''
  addList.typeNmae = ''
  addList.fileType = ''
  addList.file = ''
  addList.template = ''
  addList.displayName = ''

  // try {
  //     const typeLists = await datarApi.getfileType()
  //     typeList.value = typeLists[0]
  //     // console.log(typeList.value[0],'aaa');
  // }
  // catch (error) {
  //     console.log('失败123');
  //     // 在这里处理异常
  // }
}

const getfileTypeList = async () => {
  try {
    const typeLists = await datarApi.getfileType()
    typeList = []
    typeLists[0].children.forEach((item) => {
      typeList.push({ name: item.name, id: item.id })
      item.children.forEach((itemChildren) => {
        const combinedName = `${item.name}-${itemChildren.name}`
        typeList.push({ name: combinedName, id: itemChildren.id })
      })
    })
    typeList.sort((a, b) => a.name.length - b.name.length)
  } catch (error) {
    console.log('失败123')
    // 在这里处理异常
  }
}
// 删除
const remove = async () => {
  // 显示确认对话框
  ElMessageBox.alert('是否确定删除', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    callback: async (action) => {
      console.log(action)
      if (action === 'confirm') {
        try {
          const response = await datarApi.deleteList(idList)
          ElMessage({
            type: 'success',
            message: '已删除！'
          })
          getDataList()
        } catch (error) {}
      } else {
        ElMessage({
          type: 'info',
          message: '已取消删除！'
        })
      }
    }
  })
}

// 下载
const onDownload = async () => {
  ElMessageBox.alert('是否确定下载', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    callback: async (action) => {
      console.log(action)
      if (action === 'confirm') {
        try {
          const response = await datarApi.downloads(fileidList)
          console.log(response)
          if (filename.length === 1) {
            download.word(response, filename[0])
          } else {
            const currentTime = moment().format('YYYY-MM-DD HH:mm')
            download.zip(response, currentTime)
          }
          ElMessage({
            type: 'success',
            message: '已下载！'
          })
        } catch (error) {
          console.log('失败123')
          // 在这里处理异常
        }
      } else {
        ElMessage({
          type: 'info',
          message: '已取消下载！'
        })
      }
    }
  })
}
// top3按钮区域
// 预览
const view = async (row) => {
  let previewUrl = row.template
  let basurl = import.meta.env.VITE_BASE_URL
  let urlList = `${basurl}/admin-api/quake/file/read?pdfPath=${previewUrl}`
  window.open(urlList)
}
// 修改
const edit = (row) => {
  var reportCode = getReportCode(row.reportCode)
  flag.value = false
  addList.templateNmae = row.reportName
  addList.id = row.id
  addList.reportCode = reportCode
  addList.typeNmae = row.title
  addList.fileType = row.fileTypeId
  addList.file = addList.file
  addList.template = row.template
  addList.displayName = row.displayName
  addList.fileId = row.fileId
  const file = {
    name: row.displayName // 文件名
  }
  // // 设置文件列表
  fileList.value = [file]
  dialogVisible.value = true
}

// 获取列表数据
const getDataList = async () => {
  getLabel()
  let formdata = new FormData()
  formdata.append('reportName', formlist.reportName)
  formdata.append('reportCode', formlist.reportCode)
  formdata.append('pageSize', formlist.pageSize)
  formdata.append('pageNo', formlist.pageNo)
  // pageList.append('total', formlist.pageNo)
  // const pageList = formlist
  console.log(formdata, '123')
  try {
    const response = await datarApi.getList(formdata)
    const dataList = response.list
    tableData.value = dataList.map((item) => {
      return {
        ...item,
        reportCode: getName(item.reportCode)
      }
    })
    // 分页数据
    total.value = response.total
  } catch (error) {
    console.log('失败')
    // 在这里处理异常
  }
}

const getName = (nameType) => {
  const matchedItem = labelList.find((item) => item.type == nameType)
  console.log(matchedItem)
  // 如果找到匹配项，返回 name，否则返回 null 或其他默认值
  return matchedItem ? matchedItem.name : null
}
const getReportCode = (code) => {
  const matchedItem = labelList.find((item) => item.name == code)
  console.log(matchedItem)
  // 如果找到匹配项，返回 name，否则返回 null 或其他默认值
  return matchedItem ? matchedItem.type : null
}

let labelList

const getLabel = () => {
  labelList = []
  let labelData = getIntDictOptions(DICT_TYPE.REPORT_TYPE)
  labelData.forEach((item) => {
    labelList.push({ type: item.value, name: item.label })
  })
}
// 选取的行数据
const handleSelectionChange = (selection) => {
  idList = []
  fileidList = []
  filename = []
  selection.forEach((item) => {
    idList.push(item.id)
    fileidList.push(item.fileId)
    filename.push(item.displayName)
  })
}

// 上传
const uploadFile = (e) => {
  console.log(e.file)
  addList.file = e.file
}

// 自定义删除
const beforeRemove = (file, fileList) => {
  fileList.value = []
  addList.file = ''
}

// 保存
const onStorage = async () => {
  let formdata = new FormData()
  formdata.append('reportName', addList.templateNmae)
  formdata.append('reportCode', addList.reportCode)
  formdata.append('title', addList.typeNmae)
  formdata.append('fileTypeId', addList.fileType)
  console.log(addList.file, 'bbb')
  formdata.append('file', addList.file)
  try {
    let state = await datarApi.upTemplate(formdata)
    dialogVisible.value = false
    getDataList()
    addList.templateNmae = ''
    addList.reportCode = ''
    addList.typeNmae = ''
    addList.fileType = ''
    addList.file = '' // 清除文件对象
  } catch (error) {
    dialogVisible.value = false
  }
  dialogVisible.value = false
}

// 修改
const modify = async () => {
  let formdata1 = new FormData()
  formdata1.append('file', addList.file)
  formdata1.append('reportName', addList.templateNmae)
  formdata1.append('id', addList.id)
  formdata1.append('reportCode', addList.reportCode)
  formdata1.append('fileTypeId', addList.fileType)
  formdata1.append('title', addList.typeNmae)
  formdata1.append('template', addList.template)
  formdata1.append('displayName', addList.displayName)
  formdata1.append('fileId', addList.fileId)
  console.log(addList.fileId)
  try {
    let state = await datarApi.modify(formdata1)
    console.log(state, '-----')
    getDataList()
    dialogVisible.value = false
  } catch (error) {
    dialogVisible.value = false
  }
}

// 关闭
const onClose = () => {
  dialogVisible.value = false
}

//分页切换
const handleSizeChange = (val) => {
  pageSize.value = val
  formlist.pageSize = val
  getDataList()
}
const handleCurrentChange = (val) => {
  pageNo.value = val
  formlist.pageNo = val
  getDataList()
}
onMounted(() => {
  getDataList()
  getfileTypeList()
})
</script>

<style scoped>
:deep(.custom-header) {
  background-color: #f2f3f5 !important;
  /* 设置表头背景色 */
  color: #333 !important;
  /* 设置表头文字颜色 */
  font-weight: bold !important;
  /* 设置表头文字加粗 */
  height: 42px;
}
.el-button {
  padding: 8px 15px;
}
.btn {
  border: none;
}
</style>
